package edu.sias.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(urlPatterns = "/*")
public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request
                = (HttpServletRequest) req;
        HttpServletResponse response
                = (HttpServletResponse) resp;
        //获取访问路劲
        String path = request.getServletPath();
        System.out.println("path = " + path);
        //获取登录成功后的状态值
        Object status
                = request.getSession().getAttribute("status");

        //如果用户访问登录或注册或搜索或用户已处于登录
        if (path.contains("login")
                || path.contains("register")
                || path.contains("search")
                || path.contains("category/info")
                || null != status
        ){
            chain.doFilter(request,response);
        }else {
            //如果访问资源要求用户必须先登录
            request.setAttribute("error","用户未登录，请先登录");
            request.getRequestDispatcher("/login.jsp")
                    .forward(request,response);

        }


    }

    @Override
    public void destroy() {

    }


}
